#include "COMMON.h"

#define BACKLOG 5
int main()
{
    EnableFile();
    // 创建 socket
    int sfd = socket(AF_UNIX, SOCK_STREAM, 0);
    if(sfd == -1)
        LOG(FATAL, "socket create failed");
    
    // 移除文件
    if(remove(SV_SOCK_PATH) == -1 && errno != ENOENT)
        LOG(FATAL, "remove-%s", SV_SOCK_PATH);
    
    // 初始化地址格式
    struct sockaddr_un addr;
    memset(&addr, 0, sizeof(struct sockaddr_un));
    addr.sun_family = AF_UNIX;
    strncpy(addr.sun_path, SV_SOCK_PATH, sizeof(addr.sun_path) - 1);

    // 绑定
    if(bind(sfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) == -1)
        LOG(FATAL, "bind failed");
    if(listen(sfd, BACKLOG) == -1)
        LOG(DEBUG, "listen");

    int cfd = -1;
    int numRead = 0;
    char buf[BUF_SIZE];
    for(;;) // 迭代式地处理客户端的请求
    {
        cfd = accept(sfd, NULL, NULL);
        if(cfd == -1)
            LOG(DEBUG, "accept");
        
        while((numRead = read(cfd, buf, BUF_SIZE)) > 0)
            if(write(STDOUT_FILENO, buf, numRead) != numRead)
                LOG(FATAL, "partial/failed write");
        
        if(numRead == -1)
            LOG(INFO, "read");
        if(close(cfd) == -1)
            LOG(ERROR, "close");
    }
    return 0;
}